<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('post_favorites', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('post_id')->constrained()->cascadeOnDelete();
            $table->timestamps();

            // 确保用户对同一篇文章只能收藏一次
            $table->unique(['user_id', 'post_id']);

            // 添加索引优化查询
            $table->index('post_id');
            $table->index('user_id');
            $table->index('created_at');
        });

        // 在posts表中添加收藏统计字段
        Schema::table('posts', function (Blueprint $table) {
            $table->unsignedInteger('favorites_count')->default(0)->after('likes_count');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('favorites_count');
        });

        Schema::dropIfExists('post_favorites');
    }
};